package com.maple.file.controller;


import com.maple.common.exception.BusinessException;
import com.maple.file.service.IFileUploadService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author maple
 * @since 2023-03-24
 */
@Slf4j
@RestController
@RequestMapping("/files")
public class FileController {

    @Value("${file.upload.location}")
    private String uploadLocation;

    @Resource
    private List<IFileUploadService> fileUploadServiceList;

    private static final String NO_SUCH_SERVICE_MESSAGE = "没有对应的文件处理service,文件上传失败";

    /**
     * 文件上传到接口
     *
     * @return path
     */
    @PostMapping("/upload")
    public String upload(@RequestBody MultipartFile file) {
        String originalName = checkFileName(file);
        log.info(uploadLocation);
        List<IFileUploadService> fileUploadServices = fileUploadServiceList.stream()
                .filter(item -> item.filterService(uploadLocation))
                .collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(fileUploadServices)) {
            IFileUploadService fileUploadService = fileUploadServices.get(0);
            return fileUploadService.uploadFile(file, originalName);
        } else {
            throw new BusinessException(NO_SUCH_SERVICE_MESSAGE);
        }
    }

    private String checkFileName(MultipartFile file) {
        String originalName = file.getOriginalFilename();
        if (StringUtils.isEmpty(originalName)) {
            throw new BusinessException("文件上传失败");
        }
        return UUID.randomUUID().toString() + (!file.getOriginalFilename().contains(".") ? file.getOriginalFilename() : file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));
    }
}
